<template>
  <div class="singer-management">
    <!-- 上部：标题与操作按钮区 -->
    <div class="header-section">
      <div class="header-content">
        <h2 class="page-title">歌手管理</h2>
        <div class="button-group">
          <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedSingerIds.length === 0"
              icon="Delete"
              class="batch-delete-btn"
          >
            批量删除
          </el-button>
          <el-button type="primary" @click="handleAddSinger" class="add-singer-btn">
            <el-icon><Plus /></el-icon>
            新增歌手
          </el-button>
        </div>
      </div>
    </div>


    <!-- 中部：搜索和筛选区 -->
    <div class="search-section">
      <div class="search-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索歌手姓名"
                prefix-icon="Search"
                @keyup.enter.native="handleSearch"
                class="search-input"
            />
          </el-col>
          <el-col :span="6">
            <el-select
                v-model="filterGender"
                placeholder="筛选性别"
                clearable
                @change="handleSearch"
                class="filter-select"
            >
              <el-option label="男" value="0" />
              <el-option label="女" value="1" />
              <el-option label="乐队" value="2" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
                v-model="filterCountry"
                placeholder="筛选地区"
                clearable
                @change="handleSearch"
                class="filter-select"
            >
              <el-option label="中国" value="中国" />
              <el-option label="日韩" value="日韩" />
              <el-option label="欧美" value="欧美" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch" class="search-btn">搜索</el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 下部：表格内容区 -->
    <div class="content-section">
      <!-- 歌手列表 -->
      <el-table
          :data="singerFullList"
          border
          class="singer-table"
          :loading="loading"
          @selection-change="handleSelectChange"
          @select-all="handleSelectAll"
          :row-key="(row) => row.id"
      >
        <el-table-column
            type="selection"
            width="60"
            align="center"
        />
        <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
        />
        <el-table-column
            prop="name"
            label="歌手姓名"
            align="center"
            min-width="120"
        />
        <el-table-column
            label="歌手头像"
            align="center"
            width="100"
        >
          <template #default="scope">
            <div class="avatar-container" @click="openAvatarDialog(scope.row.id, scope.row.avatar)">
              <el-avatar :src="scope.row.avatar || '/static/default-avatar.png'" shape="square" :size="40" />
              <div class="avatar-overlay">
                <el-icon size="16"><Edit /></el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="gender"
            label="性别"
            align="center"
            width="100"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.gender === 0">男</el-tag>
            <el-tag v-else-if="scope.row.gender === 1" type="success">女</el-tag>
            <el-tag v-else-if="scope.row.gender === 2" type="info">组合</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="area"
            label="所在地区"
            align="center"
            width="120"
        />
        <el-table-column
            prop="birth"
            label="出生日期"
            align="center"
            width="140"
        />
        <el-table-column
            prop="introduction"
            label="简介"
            min-width="200"
        />
        <el-table-column
            label="操作"
            align="center"
            width="180"
        >
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEditSinger(scope.row.id)"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDeleteSinger(scope.row.id)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑歌手弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="60%"
        :before-close="handleDialogClose"
    >
      <el-form
          ref="updateFormRef"
          :model="updateForm"
          :rules="updateFormRules"
          label-width="120px"
          size="default"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="歌手姓名" prop="name">
              <el-input v-model="updateForm.name" placeholder="请输入歌手姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="updateForm.gender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
                <el-radio :label="2">组合</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在地区" prop="area">
              <el-input v-model="updateForm.area" placeholder="请输入歌手所在地区" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birth">
              <el-date-picker
                  v-model="updateForm.birth"
                  type="date"
                  placeholder="选择出生日期"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="歌手简介" prop="introduction">
          <el-input
              v-model="updateForm.introduction"
              type="textarea"
              rows="5"
              placeholder="请输入歌手简介"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSaveSinger">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改头像弹窗 -->
    <el-dialog
        v-model="avatarDialogVisible"
        title="修改歌手头像"
        width="40%"
        :before-close="handleAvatarDialogClose"
    >
      <div class="avatar-upload-container">
        <div class="current-avatar">
          <el-avatar :src="currentAvatarUrl || '/static/default-avatar.png'" shape="square" size="120" />
        </div>

        <!-- 修改：移除了method="patch"属性，避免与实际使用的方法冲突 -->
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="handleFileChange"
            :before-upload="beforeAvatarUpload"
        >
          <el-button type="primary" class="upload-button">
            <el-icon><Upload /></el-icon> 选择新头像
          </el-button>
        </el-upload>

        <div class="upload-hint">
          <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="handleAvatarDialogClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElLoading, ElMessageBox, ElIcon} from 'element-plus'
import {Plus, Edit, Delete, Search, Upload} from '@element-plus/icons-vue'
import http from "@/request/http.js";
import axios from 'axios'

// 状态管理
const singerList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索和筛选条件
const searchKeyword = ref('')
const filterGender = ref('')
const filterCountry = ref('')

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增歌手')
const currentSingerId = ref(null)

// 头像修改弹窗相关
const avatarDialogVisible = ref(false)
const currentAvatarId = ref(null)
const currentAvatarUrl = ref('')

// 表单相关
const updateFormRef = ref(null)
const updateForm = ref({
  id: '',
  name: '',
  gender: 0,
  area: '',
  birth: '',
  debut: '',
  avatar: '',
  introduction: ''
})

// 歌手列表数据
const singerFullList = ref([]);
const isBatchLoading = ref(false);
const batchErrorIds = ref([]);

// 获取单个歌手详情
const fetchSingerDetailById = async (singerId) => {
  try {
    const response = await http.get(`/artist/getArtistDetail/${singerId}`);
    const detail = response.data;
    return {
      id: detail.artistId || '',
      name: detail.artistName || '未知姓名',
      gender: detail.gender !== undefined ? detail.gender : 3,
      avatar: detail.avatar || '/static/default-avatar.png',
      birth: detail.birth || '未知',
      area: detail.area || '未知地区',
      debut: detail.debut || '未知',
      introduction: detail.introduction || '暂无简介',
      songs: detail.songs || [],
      isLoaded: true,
      loadStatus: 'success'
    };
  } catch (error) {
    batchErrorIds.value.push(singerId);
    return {
      id: singerId,
      name: `ID:${singerId} 加载失败`,
      gender: 3,
      avatar: '/static/default-avatar.png',
      birth: '未知',
      area: '未知地区',
      debut: '未知',
      introduction: error.response?.data?.msg || '详情获取失败',
      isLoaded: true,
      loadStatus: 'error',
      errorMsg: error.response?.data?.msg || '详情获取失败'
    };
  }
};

// 获取歌手列表（一次性获取所有完整信息，无需单独调用详情接口）
const fetchSingerList = async () => {
  singerFullList.value = [];
  batchErrorIds.value = [];
  isBatchLoading.value = true;
  loading.value = true;

  const loadingInstance = ElLoading.service({
    text: '正在获取歌手列表及详情...',
    lock: true
  });

  try {
    // 构造请求参数（与原逻辑保持一致）
    const requestParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      artistName: searchKeyword.value || '',
      gender: filterGender.value !== '' ? filterGender.value : null,
      area: filterCountry.value || ''
    };

    // 只调用一次/admin/getAllArtists接口，获取包含完整详情的歌手列表
    const pageResponse = await http.post('/admin/getAllArtists', requestParams);
    // 解构接口返回数据（兼容空数据场景）
    const { items: singerList = [], total: singerTotal = 0 } = pageResponse.data || {};

    // 处理空数据场景
    if (singerList.length === 0) {
      ElMessage.info('暂无歌手数据');
      total.value = 0;
      return;
    }

    // 直接处理接口返回的完整歌手数据（无需循环调用详情接口）
    // 对每个歌手做默认值处理，避免字段缺失导致的页面异常
    const fullSingerList = singerList.map(singer => ({
      id: singer.artistId || singer.id || '', // 兼容可能的id字段差异
      name: singer.artistName || singer.name || '未知姓名',
      gender: singer.gender !== undefined ? singer.gender : 3,
      avatar: singer.avatar || singer.avatarUrl || '/static/default-avatar.png',
      birth: singer.birth || '未知',
      area: singer.area || singer.country || '未知地区',
      debut: singer.debut || '未知',
      introduction: singer.introduction || '暂无简介',
      songs: singer.songs || singer.songList || [],
      isLoaded: true,
      loadStatus: 'success'
    }));

    // 赋值到列表数据和分页总数
    singerFullList.value = fullSingerList;
    total.value = singerTotal;

    // 提示成功信息
    ElMessage.success(`成功获取${fullSingerList.length}位歌手的完整信息`);

  } catch (error) {
    // 错误处理：捕获接口请求失败场景
    ElMessage.error('获取歌手列表失败：' + (error.response?.data?.msg || error.message));
    // 异常场景下清空列表，避免旧数据残留
    singerFullList.value = [];
    total.value = 0;

  } finally {
    // 无论成功失败，都关闭loading、重置加载状态
    loadingInstance.close();
    isBatchLoading.value = false;
    loading.value = false;
  }
};

// 重试加载失败的歌手详情
const retryFailedSingers = async () => {
  if (batchErrorIds.value.length === 0) {
    ElMessage.info('暂无失败的歌手详情可重试');
    return;
  }

  isBatchLoading.value = true;
  const loadingInstance = ElLoading.service({text: '正在重试加载失败的歌手详情...', lock: true});

  try {
    const retryPromiseList = batchErrorIds.value.map(id => fetchSingerDetailById(id));
    const retryResult = await Promise.all(retryPromiseList);

    retryResult.forEach(updatedSinger => {
      const index = singerFullList.value.findIndex(item => item.id === updatedSinger.id);
      if (index !== -1) {
        singerFullList.value[index] = updatedSinger;
      }
    });

    batchErrorIds.value = retryResult
        .filter(item => item.loadStatus === 'error')
        .map(item => item.id);

    const successCount = retryResult.length - batchErrorIds.value.length;
    ElMessage.success(`重试完成：${successCount}位歌手详情加载成功，剩余${batchErrorIds.value.length}位失败`);

  } catch (error) {
    ElMessage.error('重试失败：' + (error.response?.data?.msg || error.message));
  } finally {
    loadingInstance.close();
    isBatchLoading.value = false;
  }
};

// 生命周期
onMounted(() => {
  fetchSingerList();
});

// 搜索和筛选
const handleSearch = () => {
  currentPage.value = 1;
  fetchSingerList();
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchSingerList();
}

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchSingerList();
}

// 新增歌手
const handleAddSinger = () => {
  updateForm.value = {
    id: '',
    name: '',
    gender: 0,
    area: '',
    birth: '',
    avatar: '',
    introduction: ''
  };
  currentSingerId.value = null;
  dialogTitle.value = '新增歌手';
  dialogVisible.value = true;
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
}

const updateFormRules = reactive({
  name: [
    { required: true, message: "请输入歌手姓名", trigger: "blur" },
    { min: 1, max: 50, message: "歌手姓名长度在1-50个字符", trigger: "blur" },
  ],
  area: [
    { required: true, message: "请输入所在地区", trigger: "blur" },
  ],
  gender: [
    { required: true, message: "请选择性别", trigger: "change" },
  ],
  birth: [
    { required: true, message: "请选择出生日期", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请选择出生日期"));
        } else {
          const currentDate = new Date();
          const selectedDate = new Date(value);
          if (selectedDate > currentDate) {
            callback(new Error("出生日期不能晚于当前时间"));
          } else {
            callback();
          }
        }
      },
      trigger: "change",
    },
  ],
  introduction: [
    { max: 500, message: "简介不能超过500个字符", trigger: "blur" },
  ],
});

// 编辑歌手
const handleEditSinger = async (id) => {
  try {
    loading.value = true;
    const data = await fetchSingerDetailById(id);
    const birthDate = data.birth === '未知' ? '' : data.birth;
    updateForm.value = {
      id: data.id,
      name: data.name,
      gender: data.gender,
      area: data.area,
      birth: birthDate,
      avatar: data.avatar,
      introduction: data.introduction
    };
    currentSingerId.value = id;
    dialogTitle.value = '编辑歌手';
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('加载歌手详情失败：' + error.message);
  } finally {
    loading.value = false;
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false;
  setTimeout(() => {
    if (updateFormRef.value) {
      updateFormRef.value.resetFields();
    }
  }, 100);
}

// 保存歌手信息
const handleSaveSinger = async () => {
  try {
    if (!updateFormRef.value) return;
    await updateFormRef.value.validate();

    if (currentSingerId.value) {
      await http.put(`/admin/updateArtist`, updateForm.value);
      ElMessage.success('编辑歌手成功');
    } else {
      await http.post('/admin/addArtist', updateForm.value);
      ElMessage.success('新增歌手成功');
    }

    dialogVisible.value = false;
    fetchSingerList();
  } catch (error) {
    if (error.name !== 'Error') {
      return;
    }
    ElMessage.error('保存失败: ' + (error.response?.data?.msg || error.message));
  }
}

// 批量删除相关
const selectedSingerIds = ref([]);

const handleBatchDelete = async () => {
  if (selectedSingerIds.value.length === 0) {
    ElMessage.warning("请先选中要删除的歌手");
    return;
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedSingerIds.value.length} 位歌手吗？`,
        "批量删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "danger",
          draggable: true
        }
    );

    await http.delete(`/admin/deleteArtists`, {
      data: selectedSingerIds.value
    });

    ElMessage.success(`成功删除 ${selectedSingerIds.value.length} 位歌手`);
    fetchSingerList();
    selectedSingerIds.value = [];
  } catch (error) {
    if (error.message !== "cancel") {
      ElMessage.error("批量删除失败：" + (error.response?.data?.msg || error.message));
    }
  }
};

const handleSelectAll = (selection) => {
  selectedSingerIds.value = selection.map(item => item.id);
};

const handleSelectChange = (selection) => {
  selectedSingerIds.value = selection.map(item => item.id);
};

// 单个删除
const handleDeleteSinger = async (id) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这位歌手吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    await http.delete(`/admin/deleteArtist/${id}`);
    ElMessage.success('删除成功');
    fetchSingerList();
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message));
    }
  }
}

// 头像上传相关
const openAvatarDialog = (id, avatarUrl) => {
  currentAvatarId.value = id;
  currentAvatarUrl.value = avatarUrl;
  avatarDialogVisible.value = true;
}

const handleAvatarDialogClose = () => {
  avatarDialogVisible.value = false;
}

// 处理文件选择和上传 - 主要修改部分
const handleFileChange = async (uploadFile) => {
  // 验证文件
  if (!beforeAvatarUpload(uploadFile.raw)) {
    return;
  }

  const loadingInstance = ElLoading.service({
    text: '正在上传头像...',
    lock: true
  });

  try {
    // 创建FormData对象
    const formData = new FormData();
    formData.append('avatar', uploadFile.raw);

    // 修改1: 使用patch方法而不是post方法，与错误信息中的"patch"对应
    // 修改2: 调整URL格式，确保与后端接口匹配
    const response = await http.patch(
        `/admin/updateArtistAvatar/${currentAvatarId.value}`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
    );
    if (response.code === 0 ) {
      ElMessage.success('头像更新成功');
      avatarDialogVisible.value = false;
      // 重新加载歌手列表以显示新头像
      fetchSingerList();
    } else {
      ElMessage.error('头像更新失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('上传错误详情:', error);

    // 更细致的错误信息处理
    let errorMsg = '上传失败: ';
    if (error.response) {
      // 处理HTTP响应错误
      errorMsg += error.response.data?.message ||
          error.response.data?.msg ||
          `服务器错误 (状态码: ${error.response.status})`;
    } else if (error.message) {
      // 处理其他错误信息
      errorMsg += error.message;
    } else {
      errorMsg += '未知错误';
    }

    ElMessage.error(errorMsg);
  } finally {
    loadingInstance.close();
  }
}

const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }

  return isJpgOrPng && isLt2M;
}
</script>

<style scoped>
.singer-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

/* 上部标题区 */
.header-section {
  width: 100%;
  padding: 15px 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.button-group {
  display: flex;
  gap: 10px;
}

.batch-delete-btn, .add-singer-btn {
  padding: 6px 16px;
}

/* 中部搜索区 */
.search-section {
  width: 100%;
  padding: 15px;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 6px;
  box-sizing: border-box;
}

.search-container {
  width: 100%;
}

.search-input, .filter-select {
  width: 100%;
}

.search-btn {
  width: 100%;
}

/* 下部内容区 */
.content-section {
  width: 100%;
  box-sizing: border-box;
}

.singer-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination-container {
  width: 100%;
  text-align: right;
  padding: 10px 0;
}

/* 头像样式 */
.avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

/* 头像上传弹窗样式 */
.avatar-upload-container {
  text-align: center;
  padding: 20px 0;
}

.current-avatar {
  margin-bottom: 20px;
}

.upload-button {
  margin-bottom: 15px;
}

.upload-hint {
  color: #666;
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .button-group {
    width: 100%;
    justify-content: flex-start;
  }

  .search-section {
    padding: 10px;
  }
}
</style>
